import React from 'react'
import { changeNav } from '../../../actions'
import { wxGetSubProduct, wxzhctProductConf } from '../../../actions/smartDr.js'
import { connect } from 'react-redux'
import {
	Button, List, InputItem, Flex
	, WingBlank, WhiteSpace, Popup, Tag, Toast, Icon
} from 'antd-mobile'
import CSSModules from 'react-css-modules'
import styles from './openSmartdr.less'
import hhistory from '../../../history'
import { ajaxGet, ajaxPost } from 'wxAjaxUtil';

const Item = List.Item;
const Brief = Item.Brief;
let productCode = "100009";
let subProducts = {};
let subFee = 0;
let oldJtCode = '';

var cartData = {
	"productCode": productCode,
	"sellType": "",
	"sellNum": "2",
	"flag": 1,  //1开通  2续费
	"groupConfig": {},
	"storeConfig": [],
	"productConfigLabel": "子业务",
	"productConfig": [],
	"purchaseDurationLabel": "购买时长",
	"purchaseDuration": 1,
	"serviceFeeLabel": "服务费（每门店每年）",
	"serviceFee": "0",
	"activationFeeLabel": "开通费（每店）",
	"activationFee": "0",
	"payableFee": "0",
	"remark": ""
};

var cartData2 = { "productCode": "100009", "sellType": 2, "sellNum": 1, "flag": 1, "groupConfig": { "groupCode": "G000131", "groupName": "魏琴测试集团" }, "storeConfig": [{ "storeCode": "T000781", "storeName": "魏琴测试门店" }], "productConfigLabel": "子业务", "productConfig": [{ "label": "享付", "code": "100008", "value": "0.00" }], "purchaseDurationLabel": "购买时长", "purchaseDuration": 1, "serviceFeeLabel": "服务费（每门店每年）", "serviceFee": "0.00", "activationFeeLabel": "开通费（每店）", "activationFee": "0.00", "payableFee": "0.00" }

@CSSModules(styles, { allowMultiple: true })
class OpenSmartdr extends React.Component {
	constructor(props) {
		super(props);
		this.showDetailSet = this.showDetailSet.bind(this);
		this.handleSubProduct = this.handleSubProduct.bind(this);
		this.putIntoCart = this.putIntoCart.bind(this);
		this.openNow = this.openNow.bind(this);
		this.selectmd = this.selectmd.bind(this);
		this.selectjt = this.selectjt.bind(this);

		this.state = { btnDisabled: false, note: '' };
	}

	componentDidMount() {
		this.props.tochangeNav({
			title: "开通智慧餐厅", rbtn: [
				<Button key="1" type="primary" inline size="small">购0</Button>
			]
		});
		this.props.wxGetSubProduct(productCode);
	}

	//子组件向父组件传值
	handleSubProduct(subp) {
		this.props.wxzhctProductConf(subp);
	}

	//选择子产品
	showDetailSet = () => {
		Popup.show(
			<PopupWrap handleSubProduct={this.handleSubProduct} />,
			{ animationType: 'slide-up' }
		);
	}

	//选择门店
	selectmd() {
		if (Object.keys(this.props.jtData).length === 0) {
			Toast.fail('请先去添加集团！', 1);
		} else {
			oldJtCode = this.props.jtData.code;
			hhistory.push({ pathname: '/SelectDr', state: { backRouter: '/openSmartdr' } })
		}
	}

	//选择集团
	selectjt() {
		hhistory.push({ pathname: '/SelectGroup', state: { backRouter: '/openSmartdr' } })
	}

	btnClick(url, type) {
		if (Object.keys(cartData.groupConfig).length === 0) {
			Toast.fail('请先去添加集团！', 1);
			return false;
		}
		if (cartData.storeConfig.length <= 0) {
			Toast.fail('请先去添加门店！', 1);
			return false;
		}
		if (cartData.productConfig.length <= 0) {
			Toast.fail('请先去添加子产品！', 1);
			return false;
		}

		this.setState({ btnDisabled: true }); //将按钮变为不可用
		cartData.remark = this.state.note;   //获取备注信息
		console.log(cartData);

		//发送ajax请求
		if (type == 0) {
			ajaxPost(url, cartData2).then(res => {
				if (res.code && res.code == "0") {
					Toast.success('开通申请已提交', 1);
				} else {
					Toast.fail('开通失败', 1);
					this.setState({ btnDisabled: false });
				}
			})
		}
		if (type == 1) {
			ajaxPost(url, cartData2).then(res => {
				if (res.code && res.code == "0") {
					Toast.success('已加入购物车', 1);
				} else {
					Toast.fail('加入购物车失败', 1);
					this.setState({ btnDisabled: false });
				}
			})
		}
	}

	//立即开通
	openNow() {
		this.btnClick('app/product/open', 0);
	}

	//添加购物车
	putIntoCart() {
		this.btnClick('app/shopping/cart', 1);
	}

	render() {
		const { wxSubProducts, wxzhctSubProduct, jtData, mdData } = this.props;
		subProducts = wxSubProducts;
		if (subProducts.hasOwnProperty('pricingScheme') && wxSubProducts.pricingScheme && wxSubProducts.pricingScheme.length > 0) {
			cartData.sellType = wxSubProducts.pricingScheme[0].sellType;
			cartData.serviceFee = wxSubProducts.pricingScheme[0].serviceFee;
			cartData.activationFee = wxSubProducts.pricingScheme[0].activationFee;
			cartData.purchaseDuration = wxSubProducts.pricingScheme[0].serviceDuration;
		}
		cartData.productConfig = wxzhctSubProduct;

		//给cartData添加集团和门店信息
		if (Object.keys(jtData).length != 0) {
			cartData.groupConfig.groupCode = jtData.code;
			cartData.groupConfig.groupName = jtData.name;
		}
		if (mdData.length && mdData.length > 0) {
			for (var i = 0; i < mdData.length; i++) {
				cartData.storeConfig.push({
					"storeCode": mdData[i].code,
					"storeName": mdData[i].name
				});
			}
		}

		let subPSelected = function () {
			let retText = "";
			subFee = 0;
			if (wxzhctSubProduct.length > 0) {
				for (let i = 0; i < wxzhctSubProduct.length; i++) {
					subFee = Number(subFee) + Number(wxzhctSubProduct[i].value);
					if (i == wxzhctSubProduct.length - 1) {
						retText = retText + wxzhctSubProduct[i].label;
					} else {
						retText = retText + wxzhctSubProduct[i].label + ",";
					}
				}
			} else {
				retText = "请选择子产品"
			}
			cartData.payableFee = subFee.toString();
			return retText
		}

		let storeItems = (oldJtCode != jtData.code || !mdData.length || mdData.length === 0) ? '' : mdData.map((item, index) => {
			return <Item key={index} thumb={item.logo} multipleLine>
				{item.name}<Brief>{item.code}</Brief>
			</Item>
		});

		return (
			<div>
				<List renderHeader={() => '选择开通商户'} className="my-list" styleName="bgwhite">
					<Item extra="选择" arrow="horizontal" onClick={this.selectjt}>
						{(jtData == null || Object.keys(jtData).length === 0) ? '请选择集团' : <span><img src={jtData.logo} />{jtData.name}</span>}
					</Item>
					<Item extra="选择" arrow="horizontal" onClick={this.selectmd}>
						共<span styleName="red">{(oldJtCode != jtData.code || !mdData.length || mdData.length === 0) ? '0' : mdData.length}</span>个门店
			        </Item>
					{storeItems}
				</List>
				<WhiteSpace size='md' styleName="yellow" />
				<List renderHeader={() => '产品配置'} className="my-list" styleName="bgwhite">
					<Item extra="选择" arrow="down" onClick={this.showDetailSet}><div>{subPSelected()}</div></Item>
					<Item extra="购买时长">{cartData.purchaseDuration}年</Item>
					<Item>
						<div><span styleName="grey">服务费（每门店/年）</span> <span styleName="red">&yen;{cartData.serviceFee}</span></div>
						<div><span styleName="grey">开通费（每店）</span> <span styleName="red">&yen;{cartData.activationFee}</span></div>
					</Item>
				</List>
				<WhiteSpace size='md' styleName="yellow" />
				<List>
					<InputItem placeholder="备注信息选填" onBlur={value => { this.state.note = value }} />
				</List>
				<WhiteSpace size='md' styleName="yellow" />
				<List>
					<Item>
						<div>应付款总计 <span styleName="red">&yen;{Number(subFee).toFixed(2)}</span></div>
					</Item>
					<WhiteSpace size="lg" />
					<WingBlank size="lg">
						<Flex>
							<Flex.Item>
								<Button type="ghost" disabled={this.state.btnDisabled} onClick={this.putIntoCart}>加入购物车</Button>
							</Flex.Item>
							<Flex.Item>
								<Button type="primary" disabled={this.state.btnDisabled} onClick={this.openNow}>立即开通</Button>
							</Flex.Item>
						</Flex>
					</WingBlank>
					<WhiteSpace size="lg" />
				</List>
			</div>
		)
	}
}

let oldSubproducts;
let itemSelected = require('../../../components/assets/icon_shanghu_jiaobiao_2.svg');
let itemNotSelected = require('../../../components/assets/icon_shanghu_jiaobiao_1.svg');
@CSSModules(styles, { allowMultiple: true })
class RenderPop extends React.Component {
	constructor(props) {
		super(props);
		this.saveSubproduct = this.saveSubproduct.bind(this);
		this.cancleSelect = this.cancleSelect.bind(this);
		this.state = {
			subProducts: subProducts
		}
	}

	componentDidMount() {
		this.selectSubproduct();
	}

	selectSubproduct() {
		cartData.productConfig = [];
		oldSubproducts = [];
		for (let i = 0; i < subProducts.subProduct.length; i++) {
			oldSubproducts.push(Object.assign({}, subProducts.subProduct[i]));  //保存上次的修改（点取消时需要）
			if (subProducts.subProduct[i].selected) {
				cartData.productConfig.push({
					"label": subProducts.subProduct[i].productName,
					"code": subProducts.subProduct[i].productCode,
					"value": subProducts.subProduct[i].totalFee
				})
			}
		}
	}

	saveSubproduct() {
		this.selectSubproduct();
		this.props.handleSubProduct(cartData.productConfig);  //传到父组件
		Popup.hide();
	}

	cancleSelect() {
		subProducts.subProduct = oldSubproducts;
		this.setState({
			subProducts: subProducts
		});
		Popup.hide();
	}

	render() {

		let subproducts = subProducts.subProduct.map((item, index) => {
			if (!item.hasOwnProperty("selected")) {
				item.selected = false;
			}
			return <Tag key={index} className="tag" selected={item.selected ? "selected" : ""} onChange={(selected) => { item.selected = selected; this.setState({ subProducts: subProducts }) }}>{item.productName} &yen;{item.totalFee}<Icon className="jiaobiao" type={item.selected?itemSelected:itemNotSelected} /></Tag>

		});
		return <div>
			<WingBlank size="md">
				<span className="am-list-header">选择子业务</span>
			</WingBlank>
			<WhiteSpace size="lg" />
			<WingBlank size="md">
				<div styleName="tag-container">
					{subproducts}
				</div>
			</WingBlank>
			<WhiteSpace size="lg" />
			<WingBlank size="md">
				<Flex>
					<Flex.Item>
						<Button type="primary" onClick={this.cancleSelect}>取消</Button>
					</Flex.Item>
					<Flex.Item>
						<Button type="primary" onClick={this.saveSubproduct}>确定</Button>
					</Flex.Item>
				</Flex>
			</WingBlank>
			<WhiteSpace size="lg" />
		</div>
	}
}

const PopupWrap = CSSModules(RenderPop, styles)

const mapStateToProps = (state) => ({
	wxSubProducts: state.wxSmartdrs.wxSubProducts,
	wxzhctSubProduct: state.wxSmartdrs.wxzhctSubProduct,
	jtData: state.wxSmartdrs.jtData,
	mdData: state.wxSmartdrs.mdData
})
const mapDispatchToProps = (dispatch) => ({
	tochangeNav: navogj => dispatch(changeNav(navogj)),
	wxGetSubProduct: productCode => dispatch(wxGetSubProduct(productCode)),
	wxzhctProductConf: productConfig => dispatch(wxzhctProductConf(productConfig))
})

export default connect(mapStateToProps, mapDispatchToProps)(OpenSmartdr)